import { Button, Card,  List, Popconfirm, message } from 'antd'
import './index.scss'
import { useDispatch, useSelector } from 'react-redux'
import { useEffect, useState } from 'react'
import { fetchMessageInfo } from '@/store/modules/messageStore'
import dayjs from 'dayjs'
import {DeleteOutlined} from '@ant-design/icons'
import { getMessageDeleteAPI } from '@/api/message'
import moment from 'moment'

const Information = () => {
  // 获取用户Id
  const dispatch = useDispatch()
  const userId = useSelector(state => state.user.userInfo.id)
  
  const getMessageInfo = async () => {
    await dispatch(fetchMessageInfo(userId))
  }
  useEffect(() => {
    getMessageInfo()
  }, [])
  const messageInfo = useSelector(state => state.message.messageInfo)
   // 通过时间对博客进行排序
   if (message.length) {
    messageInfo.sort((a, b) => moment(b.createTime).diff(moment(a.createTime)))
   }

  // 删除消息
  const deleteInfo = async (id) => {
    const res = await getMessageDeleteAPI(id)
    if (res.code === 1) {
      message.success('删除成功！')
      getMessageInfo()
    }
  }

  // 分页
  const [params, setParams] = useState({
    page: 1,
    per_page: 2
  })
  const pageChange = (page) => {
    // 拿到当前页参数 修改params 
    setParams({
      ...params,
      page
    })
}

  return (
    <div className="information">
        <Card
        title='消息通知'>
          <List
            itemLayout="vertical"
            size="large"
            pagination={{
              current: params.page,
              pageSize: params.per_page,
              onChange: pageChange,
              total: messageInfo.length
            }}
            dataSource={messageInfo}
            renderItem={(item) => (
              <List.Item
                key={item.id}
              >
                <div className="header">
                  <List.Item.Meta
                    title='您收到一个消息'
                    description={dayjs(item.createTime).format('YYYY-MM-DD')}
                  />
                  <Popconfirm
                    title="确认删除该条消息吗?"
                    onConfirm={() => deleteInfo(item.id)}
                    okText="确认"
                    cancelText="取消"
                  >
                    <Button 
                      size='small' 
                      icon={<DeleteOutlined />}/>
                  </Popconfirm>
                </div>
                <div className="text">
                  <span>{item.text}</span>
                </div>
              </List.Item>
            )}
          />
      </Card>
    </div>
  )
}

export default Information